<?php
/**
 * Created by PhpStorm.
 * User: OOO
 * Date: 2019/2/25
 * Time: 11:28
 */

namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\admin;

class mondayController extends  Controller{
    public function admin(){
        return view('monday.admin');
    }

    public function  top(){
        return view('monday.top');
    }

    public function  left(){
        return view('monday.left');
    }

    public function  news_list(){
        $info = DB::table('news')->paginate(3);
        return view('monday/news_list',['info'=>$info]);
    }


    public function  news_add(){
        if ($_POST) {
            //实现图片上传
            $data=DB::table('news')->where('news_title','=',$_POST['news_title'])->first();
            if($data){
                echo "<script>alert('标题已经存在。请使用其它标题！');location.href='" . url('one_news_add'/*,Session::get('id')*/). "';</script>";
            }else{
                $path = "img/{$_FILES['face']['name']}";
                move_uploaded_file($_FILES['face']['name'],$path);
                $time=date('Y-m-d H:i:s', time());
                $p_name=$_POST['p_name']."-".$_POST['a_name']."-".$_POST['b_name'];
                $array = array(
                    'news_title' => $_POST['news_title'],
                    'p_name' => $p_name,
                    'cate_name' => $_POST['cate_name'],
                    'content' => $_POST['content'],
                    'created_at' =>$time,
                    'news_man' => $_POST['news_man'],
                    'face' => $_POST['face'] = $path
                );
                $info = DB::table('news')->insert($array);
                if ($info) {
                    return redirect('one_news_list');
                }
            }
        } else {
            $type=DB::table('type')->where('pid','=',0)->get();
            return view('monday.news_add',['type'=>$type]);
        }
    }
    public function news_yes(){
        $info=DB::table('type')->where('pid','=',$_GET['id'])->get();
        $str="";
        foreach ($info as $v){
            $str.="<option value='{$v->id}'>{$v->name}</option>";
        }
        return $str;
    }
    public function news_del(){
            $id = $_GET;
            $data = DB::table('news')->where(['id' => $id])->delete();
            if ($data) {
                return redirect('one_news_list');
            } else {
                return view('one_news_list');
            }
    }

    public function news_edit(Request $r){
        if ($r->isMethod('post')){
            $data=$r->all();
            unset($data['_token']);
            $info=DB::table('news')->where('id',$data['id'])->update($data);
            if ($info){
                return redirect('one_news_list');
            }else{
                dd("修改失败");
            }
        }else{
            $id=$_GET['id'];
            // var_dump($id);die();
            $info=DB::table('news')->where('id',$id)->first();
            //dd($info);die;
            return view('monday/news_edit_list',['info'=>$info]);
        }
    }



    public function  cate_list(){
        $info = DB::table('cate')->get();
        return view('monday.cate_list',['info'=>$info]);
    }

    public function  cate_add(){
        if ($_POST) {
            $time=date('Y-m-d H:i:s', time());
            $array = array(
                'p_name' => $_POST['p_name'],
                'news_title' => $_POST['news_title'],
                'created_at' =>$time,
                'news_man' => $_POST['news_man']
            );
            $info = DB::table('cate')->insert($array);
            if ($info) {
                return redirect('one_cate_list');
            }
        }else{
            return view('monday.cate_add ');
        }
    }

    public function cate_del(){
        $id = $_GET;
        $data = DB::table('cate')->where(['id' => $id])->delete();
        if ($data) {
            return redirect('one_cate_list');
        } else {
            return view('one_cate_list');
        }
    }


    public function cate_edit(Request $r){
        if ($r->isMethod('post')){
            $data=$r->all();
            unset($data['_token']);
            $info=DB::table('cate')->where('id',$data['id'])->update($data);
            if ($info){
                return redirect('one_cate_list');
            }else{
                dd("修改失败");
            }
        }else{
            $id=$_GET['id'];
            // var_dump($id);die();
            $info=DB::table('cate')->where('id',$id)->first();
            //dd($info);die;
            return view('monday/cate_edit_list',['info'=>$info]);
        }
    }




    public function  admin_list(){
        $info = DB::table('admin')->get();
        return view('monday.admin_list ',['info'=>$info]);
    }

    public function  admin_add(){
        if($_POST){
            $arr['username']=$_POST['username'];
            $arr['psd']=$_POST['psd'];
            $arr['sex']=$_POST['sex'];
            $arr['hobby']=$_POST['hobby'];
            $arr['city']=$_POST['city'];
            $arr['introduce']=$_POST['introduce'];
            $arr['js']=$_POST['js'];
            $info = DB::table('admin')->insert($arr);
            if($info){
                echo "2";
            }else{
                echo "404";
            }
        }else{
            return view('monday.admin_add ');
        }
    }

    public function admin_del(){
        $id = $_GET;
        $data = DB::table('admin')->where(['id' => $id])->delete();
        if ($data) {
            return redirect('one_admin_list');
        } else {
            return view('one_admin_list');
        }
    }


    public function admin_edit(Request $r){
        if ($r->isMethod('post')){
            $data=$r->all();
            unset($data['_token']);
            $info=DB::table('admin')->where('id',$data['id'])->update($data);
            if ($info){
                return redirect('one_admin_list');
            }else{
                dd("修改失败");
            }
        }else{
            $id=$_GET['id'];
            // var_dump($id);die();
            $info=DB::table('admin')->where('id',$id)->first();
            //dd($info);die;
            return view('monday/admin_edit_list',['info'=>$info]);
        }
    }



    public function export(){//导出
        $data=admin::get()->toArray();
        $title=array('id','名称','密码','性别','爱好','城市','介绍','角色');
        return response()->download($headers = ['Content-Type'=>'application/zip;charset=utf-8']);
    }

    public function import(Request $r){//导入
        $a=$r->all();
        $info=$this->importExecl($a);
        unset($info[0]);
        unset($info[1]);
        unset($info[2]);
        unset($info[3]);
        unset($info[4]);
        unset($info[5]);
        unset($info[6]);
        unset($info[7]);
        $arr=array();
        foreach ($info as $k=>$v){
            $arr[$k]['id']=$v['A'];
            $arr[$k]['username']=$v['B'];
            $arr[$k]['pwd']=$v['C'];
            $arr[$k]['sex']=$v['D'];
            $arr[$k]['hobby']=$v['E'];
            $arr[$k]['city']=$v['F'];
            $arr[$k]['introduce']=$v['G'];
            $arr[$k]['js']=$v['H'];
        }
        $list=array();
        foreach ($arr as $v){
            $list=$v;
            admin::insert($list);
        }
        $data = admin::get();
        return view("money.admin_list", ["info" => $data]);
    }

    /**
     * 数据导出
     * @param array $title   标题行名称
     * @param array $data   导出数据
     * @param string $fileName 文件名
     * @param string $savePath 保存路径
     * @param $type   是否下载  false--保存   true--下载
     * @return string   返回文件全路径
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    function exportExcel($title=array(), $data=array(), $fileName='', $savePath='./', $isDown=false){
        error_reporting(0);
        include('PHPExcel.php');
        $obj = new \PHPExcel();

        //横向单元格标识
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

        $obj->getActiveSheet(0)->setTitle('sheet名称');   //设置sheet名称
        $_row = 1;   //设置纵向单元格标识
        if($title){
            $_cnt = count($title);
            $obj->getActiveSheet(0)->mergeCells('A'.$_row.':'.$cellName[$_cnt-1].$_row);   //合并单元格
            $obj->setActiveSheetIndex(0)->setCellValue('A'.$_row, '数据导出：'.date('Y-m-d H:i:s'));  //设置合并后的单元格内容
            $_row++;
            $i = 0;
            foreach($title AS $v){   //设置列标题
                $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);
                $i++;
            }
            $_row++;
        }

        //填写数据
        if($data){
            $i = 0;
            foreach($data AS $_v){
                $j = 0;
                foreach($_v AS $_cell){
                    $obj->getActiveSheet(0)->setCellValue($cellName[$j] . ($i+$_row), $_cell);
                    $j++;
                }
                $i++;
            }
        }

        //文件名处理
        if(!$fileName){
            $fileName = uniqid(time(),true);

        }

        $objWrite = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');

        if($isDown){   //网页下载
            header('pragma:public');
            header("Content-Disposition:attachment;filename=$fileName.csv");
            $objWrite->save('php://output');exit;
        }

        $_fileName = iconv("utf-8", "gb2312", $fileName);   //转码
        $_savePath = $savePath.$_fileName.'.csv';
        $objWrite->save($_savePath);

        return $savePath.$fileName.'.csv';
    }

    /**
     *  数据导入
     * @param string $file excel文件
     * @param string $sheet
     * @return string   返回解析数据
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    function importExecl($file='', $sheet=0){
        $file = iconv("utf-8", "gb2312", $file);   //转码
        if(empty($file) OR !file_exists($file)) {
            die('file not exists!');
        }
        include('PHPExcel.php');  //引入PHP EXCEL类
        $objRead = new \PHPExcel_Reader_Excel2007();   //建立reader对象
        if(!$objRead->canRead($file)){
            $objRead = new PHPExcel_Reader_Excel5();
            if(!$objRead->canRead($file)){
                die('No Excel!');
            }
        }

        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

        $obj = $objRead->load($file);  //建立excel对象
        $currSheet = $obj->getSheet($sheet);   //获取指定的sheet表
        $columnH = $currSheet->getHighestColumn();   //取得最大的列号
        $columnCnt = array_search($columnH, $cellName);
        $rowCnt = $currSheet->getHighestRow();   //获取总行数

        $data = array();
        for($_row=1; $_row<=$rowCnt; $_row++){  //读取内容
            for($_column=0; $_column<=$columnCnt; $_column++){
                $cellId = $cellName[$_column].$_row;
                $cellValue = $currSheet->getCell($cellId)->getValue();
                //$cellValue = $currSheet->getCell($cellId)->getCalculatedValue();  #获取公式计算的值
                if($cellValue instanceof PHPExcel_RichText){   //富文本转换字符串
                    $cellValue = $cellValue->__toString();
                }

                $data[$_row][$cellName[$_column]] = $cellValue;
            }
        }

        return $data;
    }
}